<template>
  <div>
    <el-upload class="upload" drag :action="uploadUrl" :on-error="handleFileUpload" :on-success="handleFileUpload" :limit="1"
               accept="image/jpeg,image/gif,image/png" :on-exceed="handleExceed">
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过1MB</div>
    </el-upload>
    <el-container>
      <el-form :model="articleForm" :rules="rules" ref="articleForm" label-width="100px" class="edit-form">
        <el-form-item label="文章类型" class="category">
          <el-select v-model=articleForm.type placeholder="请选择文章类型" >
            <el-option v-for="type in types" :label="type.name" :value="type.id" :key="type.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="作者" prop="author" class="author">
          <el-input v-model="articleForm.author" placeholder="请输入作者"></el-input>
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="articleForm.title" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="标签" prop="tags">
          <el-input v-model="articleForm.tags" placeholder="请输入标签"></el-input>
        </el-form-item>
        <el-form-item prop="content" v-if="articleForm.type !==3">
          <div class="edit_container" >
            <quill-editor
              v-model="articleForm.content"
              ref="myQuillEditor"
              :options="editorOption"
              @blur="onEditorBlur($event)" @focus="onEditorFocus($event)"
              @change="onEditorChange($event)">
            </quill-editor>
          </div>
        </el-form-item>
        <el-form-item label="外链链接" prop="content" v-else class="out-link">
          <el-input v-model="articleForm.content" placeholder="请输入标题" size="100px"></el-input>
          <el-alert
            title="注意外链只是外部文章的超链接"
            type="warning"
            :closable="false"
          >
          </el-alert>
        </el-form-item>
        <el-form-item>
          <el-button  @click="saveHtml('articleForm')">保存</el-button>
        </el-form-item>
        <el-form-item v-if="this.articleForm.id !== ''">
          <el-button v-if="articleForm.html.url != null" type="text" @click="deployArticle">重新生成静态页面</el-button>
          <el-button v-else type="text" @click="deployArticle" >生成静态页面</el-button>
        </el-form-item>
        <el-input type="hidden" :value="articleForm.html.templateId"/>
      </el-form>
    </el-container>
  </div>
</template>

<script>
import EventBus from '../EventBus'
export default {
  name: 'RichEditor',
  data () {
    return {
      uploadUrl: getGServerUrl() + '/file/upload',
      content: '',
      types: [
        {
          id: 1,
          name: '原创'
        }, {
          id: 2,
          name: '转载'
        }, {
          id: 3,
          name: '外链'
        }, {
          id: 4,
          name: '其他'
        }
      ],
      typeName: '',
      typeId: 0,
      editorOption: {},
      computed: {
        editor () {
          return this.$refs.myQuillEditor.quill
        },
        model: 'Edit Your Content Here!'
      },
      articleForm: {
        id: '',
        title: '',
        author: '',
        content: '',
        type: '',
        cover: '',
        tags: '',
        createTime: '',
        updateTime: '',
        isDelete: '',
        html: {
          url: '',
          templateId: '1'
        }
      },
      articleTypeArr: ['原创', '转载'],
      rules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择文章类型', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入文章内容', trigger: 'blur' }
        ]
      }
    }
  },
  props: {
    cObj: Object,
    cAction: String
  },
  watch: {
    'CObj' () {
      console.log('change--!')
    },
    cAction: function (val, oldVal) {
      if (val === 'create') {
        this.resetArticleForm()
      }
      console.log('form:%o', this.articleForm)
    }
  },
  methods: {
    onEditorBlur () {},
    onEditorFocus () {},
    onEditorChange () {},
    saveHtml: function (formName) {
      this.submitForm(formName)
    },
    resetArticleForm: function () {
      this.articleForm.id = ''
      this.articleForm.title = ''
      this.articleForm.author = ''
      this.articleForm.content = ''
      this.articleForm.type = ''
      this.articleForm.cover = ''
      this.articleForm.tags = ''
      this.articleForm.createTime = ''
      this.articleForm.updateTime = ''
      this.articleForm.isDelete = ''
      this.articleForm.html.templateId = 1
    },
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let url = getGServerUrl()
          if (this.articleForm.id === '') {
            url += '/article/add/deploy'
          } else {
            url += '/article/update'
          }
          this.axios.post(url, this.articleForm)
            .then(response => {
              let data = response.data.data
              console.log(response)
              let count = data.count
              if (count > 0) {
                this.$message({
                  message: '发布成功: ' + count,
                  type: 'success'
                })
                this.resetForm(formName)
                EventBus.$emit('toggleTab', 'Article')
              } else {
                this.$message({
                  message: '发布失败:' + data.msg,
                  type: 'error'
                })
              }
            })
            .catch(error => {
              this.$message({
                message: '发布失败:' + error,
                type: 'error'
              })
            })
        } else {
          this.$message({
            message: '发布失败，请检查输入是否正确',
            type: 'error'
          })
        }
      })
    },
    deployArticle: function () {
      let postData = null
      let url = getGServerUrl()
      debugger
      if (this.articleForm.html.url === null || this.articleForm.html.url === undefined) {
        url += '/article/deploy'
        this.articleForm.html = {templateId: 1}
        postData = this.articleForm
      } else {
        url += '/article/redeploy'
        postData = {articleId: this.articleForm.id, templateId: this.articleForm.html.templateId}
      }
      this.axios.post(url, postData)
        .then(resp => {
          let data = resp.data.data
          if (data.count > 0) {
            this.articleForm.html.articleId = data.id
            this.$message.success('生成静态页面成功')
          } else {
            this.$message.error('生成静态页面失败')
          }
        })
        .catch(error => {
          this.$message.error('生成静态页面失败' + error.data.data.msg)
        })
    },
    handleFileUpload: function (response, file, fileList) {
      if (response.code === 200) {
        this.articleForm.cover = response.data.url
        this.$message({
          message: '上传成功！',
          type: 'success'
        })
      } else {
        this.$message({
          message: '上传失败！',
          type: 'error'
        })
      }
      console.log(response, file, fileList)
    },
    resetForm: function (formName) {
      this.resetArticleForm()
    },
    handleExceed: function () {
      this.$message.error('只能上传一个文件，如需重新选择文件请先删除已选文件再上传')
    }
  },
  mounted () {
    if (this.cAction === 'create' || this.cAction === null || this.cAction === undefined) {
      this.resetArticleForm()
      console.log('action:%o', this.articleForm)
    } else {
      console.log('cObj:%o', this.cObj)
      this.articleForm = this.cObj
      if (this.articleForm.html === null) {
        this.articleForm.html = {
          templateId: 1
        }
      }
    }
  }
}
</script>

<style scoped>
  .upload{
    text-align: center;
    margin-bottom: 20px;
  }
.el-container{
  margin: 0 auto;
  text-align: center;
}
  .quill-editor{
    height: 25rem;
  }
  .el-button{
    margin-top: 5rem;
  }
  .edit-form{
    width: 100%;
  }
  .category{
    text-align: left;
  }
  .author{
    max-width: 400px;
  }
  .out-link{
    width: 100%;
    display: block;
  }
</style>
